package com.lw.oop.dayfive.bdemo;

import java.sql.*;

/**
 * @author liuwei
 * @ClassName UserTest.java
 * @description: TODO
 * @date 2023年06月19日
 * @version: 1.0
 */
public class UserTest {
    public void UserJdbc(String username, String password) throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/jdbc_test?useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String pas = "root";
        //有sql注入的风险
        //Statement statement = null;
        //防止sql注入
        PreparedStatement pstmt = null;
        //获取执行者
        Connection conn = DriverManager.getConnection(url, user, pas);
        if (conn != null) {
            System.out.println("连接成功");
            //获取发送 SQL 的对象
            //statement = conn.createStatement();
            //查询数据
            //String sql = "select * from user where username='" + username + "'and password='" + password+"'";
            //System.out.println(sql);
            //ResultSet result = statement.executeQuery(sql);
            pstmt = conn.prepareStatement("select * from user where username=? and password=?");
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet result = pstmt.executeQuery();
            while (result.next()) {
                String name = result.getString("username");
                System.out.println("登录成功 + 用户名：" + name);
                return;
            }
            System.out.println("登录失败");
        } else {
            System.out.println("连接失败");
        }
        pstmt.close();
        conn.close();
    }


    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        UserTest user = new UserTest();
        user.UserJdbc("admin", "'admin' or 1=1");
    }

}
